package com.igoal.web;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.tuckey.web.filters.urlrewrite.utils.StringUtils;

import com.igoal.dto.NewsDTO;
import com.igoal.service.MessageManager;
import com.igoal.service.NewsManager;
import com.igoal.service.TagService;
import com.igoal.service.UserManagerExt;
import com.igoal.utils.ConvertUtils;
import com.igoal.web.model.NewsModel;

@Controller
@RequestMapping("/ajax/news.html")
public class AjaxNewsController extends BaseAjaxController {
	private NewsManager newsManager;
	private TagService tagService;
	
	@Autowired
	public void setTagService(TagService tagService) {
		this.tagService = tagService;
	}

	@Autowired
	public void setNewsManager(NewsManager newsManager) {
		this.newsManager = newsManager;
	}
	
	@Autowired
	public void setUserManagerExt(UserManagerExt userManagerExt) {
		this.userManagerExt = userManagerExt;
	}
	
	@Autowired
	public void setMessageManager(MessageManager messageManager) {
		this.messageManager = messageManager;
	}
	
	@RequestMapping(method=RequestMethod.GET)
	public String show(ModelMap modelMap, @RequestParam(value="tagId", required=false) Long tagId, @RequestParam(value="tagName", required=false) String tagName, @RequestParam("lastOrderValue") String lastOrderValue){
		NewsModel model = new NewsModel();
		List<NewsDTO> news = null;	
		Date date = null;
		if(!StringUtils.isBlank(lastOrderValue)){
			Long time = ConvertUtils.toLong(lastOrderValue, -1L);
			if(time > 0L){
				date = new Date(time);
			}
		}
		
		if(tagName == null && (tagId == null || tagId == -1L)){
			news = newsManager.listNews(date, false);			
		}else if(!StringUtils.isBlank(tagName)){
			news = tagService.listTaggedNews(null, tagName, date, false);
		}else if(tagId > 0L){
			news = tagService.listTaggedNews(tagId, null, date, false);
			modelMap.addAttribute("tagId", tagId);
		}
		
		model.setNews(news);
		
		initSessionInformation(model);
		
		applyModel(modelMap, model);
		
		return getViewPrefix() + "ajaxNewsView";
	}
}
